//
//  UITextView+keyboard.swift
//  表情键盘
//
//  Created by 叶周翔 on 16/7/30.
//  Copyright © 2016年 叶周翔. All rights reserved.
//

import UIKit

extension UITextView {
    
    func emoticonText() -> String{
        
        var resultString = ""
        self.attributedText.enumerateAttributesInRange(NSRange(location: 0, length: self.attributedText.length), options: []) { (dict, range, _) -> Void in
            if let attachment = dict["NSAttachment"] as? YZXTextAttachment{
                
                let chs = attachment.chs
                // 拼接起来
                resultString += chs!
            }else{
                let str = (self.attributedText.string as NSString).substringWithRange(range)
                resultString += str
            }
        }
        return resultString
    }
    
    
    
    func inserEmoticon(model:YZXEmoticonModel) {
        if let emoji = model.emoji{
            self.insertText(emoji)
            return
        }
        
        if let fullPath = model.fullPngPath{
            let image = UIImage(named: fullPath)
            // 属性文本可以添加附件
            // 将图片放到附件中
            let attachment = YZXTextAttachment()
            attachment.image = image
            // 表情 名称 用于网络的传输
            attachment.chs = model.chs
            // 获取文字的大小
            let imageWH = self.font?.lineHeight ?? 0
            // 设置附件的bounds
            attachment.bounds = CGRect(x: 0, y: CGFloat(-4), width: imageWH, height: imageWH)
            // 3. 用一个附件生成一个属性文本 如果不给附件添加属性后续的图片表情会变的很小
            let attrText = NSAttributedString(attachment: attachment)
            let attrTextM = NSMutableAttributedString(attributedString: attrText)
            attrTextM.addAttribute(NSFontAttributeName, value: self.font!, range: NSRange(location: 0, length: 1))
            // 获取到textView上面当前的内容
            let currentAttText = NSMutableAttributedString(attributedString: self.attributedText)
            let currentSelectRange = self.selectedRange
            
            // 获取到光标的位置
            currentAttText.replaceCharactersInRange(currentSelectRange, withAttributedString: attrTextM)
            
            self.attributedText = currentAttText
            // 重新设置光标的位置
            self.selectedRange = NSRange(location: currentSelectRange.location+1, length:0)
            
            // 发送通知
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: self)
            // 调用代理方法
            delegate?.textViewDidChange?(self)
        }
        
        
    }
}
